using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BubblePool : MonoBehaviour
{
	private static BubblePool instance;

	public Bubble boublePrefab;

	private Queue<Bubble> boubles;

	private Bubble tempBubble;

	private Vector3 initialPos;

	private int count;

	private List<Bubble> initializeList;

	public static BubblePool Instance
	{
		get
		{
			return instance;
		}
	}

	private void Awake()
	{
		if (instance == null)
		{
			instance = this;
		}
		else
		{
			Object.Destroy(base.gameObject);
		}
	}

	private void Start()
	{
		boubles = new Queue<Bubble>();
		initialPos = new Vector3(1000f, 1000f, 0f);
		initializeList = new List<Bubble>();
		for (int i = 0; i < 5; i++)
		{
			boubles.Enqueue(CreateBubble());
		}
		StartCoroutine(SpawnBubbleRoutine());
	}

	private void FixedUpdate()
	{
		if (initializeList.Count > 0)
		{
			for (int i = 0; i < initializeList.Count; i++)
			{
				initializeList[i].SetPosition();
			}
			initializeList.Clear();
		}
	}

	public Bubble CreateBubble()
	{
		count++;
		return Object.Instantiate(boublePrefab, initialPos, Quaternion.identity, base.transform);
	}

	public void ReturnBubble(Bubble bouble)
	{
		bouble.transform.position = initialPos;
		bouble.transform.localScale = Vector3.one;
		boubles.Enqueue(bouble);
	}

	public Bubble GetBubble()
	{
		if (boubles.Count > 0)
		{
			tempBubble = boubles.Dequeue();
			initializeList.Add(tempBubble);
			return tempBubble;
		}
		return null;
	}

	private IEnumerator SpawnBubbleRoutine()
	{
		while (true)
		{
			yield return new WaitForSeconds(3f);
			if (boubles.Count > 0)
			{
				SpawnBubble();
			}
		}
	}

	private void SpawnBubble()
	{
		tempBubble = GetBubble();
		if (tempBubble != null)
		{
			Vector3 vector;
			do
			{
				vector = GameManager.GetRandomPosition(1f);
			}
			while (Physics2D.OverlapCircle(vector, 6f, 5376) != null);
			tempBubble.Initialize(Random.Range(Values.Instance.BubbleAverageMass - Values.Instance.BubbleDeviationAmount, Values.Instance.BubbleAverageMass + Values.Instance.BubbleDeviationAmount), vector);
		}
	}
}
